{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-06-23T08:10:27.419675Z",
     "start_time": "2025-06-23T08:10:26.218744Z"
    }
   },
   "source": [
    "import torch\n",
    "\n",
    "x = torch.arange(4.0)\n",
    "x"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0., 1., 2., 3.])"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-23T08:10:27.574867Z",
     "start_time": "2025-06-23T08:10:27.561257Z"
    }
   },
   "cell_type": "code",
   "source": [
    "x.requires_grad_(True)  # 等价于x=torch.arange(4.0,requires_grad=True)\n",
    "print(x.grad)# 默认值是None"
   ],
   "id": "6ded047191e416f1",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-23T08:10:27.606513Z",
     "start_time": "2025-06-23T08:10:27.591743Z"
    }
   },
   "cell_type": "code",
   "source": [
    "y = 2 * torch.dot(x, x)\n",
    "y"
   ],
   "id": "c106e0110de7dbe4",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(28., grad_fn=<MulBackward0>)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-23T08:10:27.653352Z",
     "start_time": "2025-06-23T08:10:27.623263Z"
    }
   },
   "cell_type": "code",
   "source": [
    "y.backward()\n",
    "x.grad"
   ],
   "id": "469c08b5522be64a",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([ 0.,  4.,  8., 12.])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-23T08:10:27.685375Z",
     "start_time": "2025-06-23T08:10:27.670564Z"
    }
   },
   "cell_type": "code",
   "source": "x.grad == 4 * x",
   "id": "71177bbe7c0dee8e",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-23T08:10:27.717520Z",
     "start_time": "2025-06-23T08:10:27.702686Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 在默认情况下，PyTorch会累积梯度，我们需要清除之前的值\n",
    "x.grad.zero_()\n",
    "y = x.sum()  #x1+x2+......\n",
    "y.backward() # 1矩阵\n",
    "x.grad"
   ],
   "id": "1e3d1749b52d9616",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([1., 1., 1., 1.])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-23T08:10:27.748272Z",
     "start_time": "2025-06-23T08:10:27.734563Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 对非标量调用backward需要传入一个gradient参数，该参数指定微分函数关于self的梯度。\n",
    "# 本例只想求偏导数的和，所以传递一个1的梯度是合适的\n",
    "x.grad.zero_()\n",
    "y = x * x\n",
    "print(y),print(y.sum())\n",
    "# 等价于y.backward(torch.ones(len(x)))\n",
    "y.sum().backward() #转标量\n",
    "x.grad"
   ],
   "id": "fc3165b0de62c904",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([0., 1., 4., 9.], grad_fn=<MulBackward0>)\n",
      "tensor(14., grad_fn=<SumBackward0>)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "tensor([0., 2., 4., 6.])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-23T08:10:27.779422Z",
     "start_time": "2025-06-23T08:10:27.764239Z"
    }
   },
   "cell_type": "code",
   "source": [
    "x.grad.zero_()\n",
    "y = x * x\n",
    "u = y.detach() #把y当做常数，而与x无关\n",
    "z = u * x\n",
    "\n",
    "z.sum().backward()\n",
    "x.grad == u"
   ],
   "id": "87fdfe47b8dbf7d1",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-23T08:10:27.810435Z",
     "start_time": "2025-06-23T08:10:27.796796Z"
    }
   },
   "cell_type": "code",
   "source": [
    "x.grad.zero_()\n",
    "y.sum().backward()\n",
    "x.grad == 2 * x"
   ],
   "id": "e65a45119cde605a",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-23T08:10:27.841303Z",
     "start_time": "2025-06-23T08:10:27.827523Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def f(a):\n",
    "    b = a * 2\n",
    "    while b.norm() < 1000:\n",
    "        b = b * 2\n",
    "    if b.sum() > 0:\n",
    "        c = b\n",
    "    else:\n",
    "        c = 100 * b\n",
    "    return c\n",
    "\n",
    "a = torch.randn(size=(), requires_grad=True)\n",
    "d = f(a)\n",
    "d.backward()\n",
    "\n",
    "a,d,a.grad == d / a"
   ],
   "id": "42b70cc6c915731d",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor(-1.9343, requires_grad=True),\n",
       " tensor(-198074.0469, grad_fn=<MulBackward0>),\n",
       " tensor(True))"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-23T08:10:27.872261Z",
     "start_time": "2025-06-23T08:10:27.858293Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "1527b0d6a8b46a34",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
